package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.PhotoUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.UploadUtils;
import com.cloudxingkong.dianyinke.NewTeacher.bean.QryTeacher;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class UploadResume extends AppCompatActivity {
    /** 资格证*/
    private static final int SELECT_PIC_BY_TAKE_PHOTO=1;
    private static final int SELECT_PIC_BY_PICK_PHOTO=2;
    private Uri photoUri;
    private RadioGroup radioGroup;
    private ImageView ivTapPro,ivTapTeach,ivTapIdcard,ivCover;
    private ImageView btnPro,btnIdcard,btnTeach;
    private EditText etName,etQianming,etWorkexp1,etAliasname,etSeniority,etGlory,etPresentjob;
    private String name,workExp1,qianMing,picPath,aliasname,seniority,glory,presentJob;

    private String pfcfPic,teflPic,idenPic,coverPic;

    private RadioButton rbBoy,rbGirl;
    private String sexID="";
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;
    private static int clickTag = -1;

    private ImageView imageViews[]={ivCover,ivTapIdcard};

    private boolean flag=false;
    private EditText etInst;
    private String inst;
    private String qryTid;

    private ArrayList<String> pathList;
    private static final int REQUEST_IMAGE=2;
    private String sessionID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_resume);
        init();
        //loadImages();
    }

    private void loadImages() {//加载图片
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.THIS_RESUME);
        params.addHeader("cookie", sessionID);

        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Message msg = handler.obtainMessage();
                msg.what = 2;
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e("test","获取老师资料失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void init() {
        radioGroup = (RadioGroup) findViewById(R.id.ur_radio_group);
        ivTapPro = (ImageView) findViewById(R.id.ur_iv_tap_pro);    //专业证
        ivTapTeach = (ImageView) findViewById(R.id.ur_iv_tap_teach);    //教师资格证
        ivTapIdcard = (ImageView) findViewById(R.id.ur_iv_tap_idcard);   //身份证
        ivCover = (ImageView) findViewById(R.id.ur_ivcover);           //头像

        btnPro = (ImageView) findViewById(R.id.ur_tap_pro);
        btnIdcard = (ImageView) findViewById(R.id.ur_tap_idcard);
        btnTeach = (ImageView) findViewById(R.id.ur_tap_teach);

        etName = (EditText) findViewById(R.id.ur_et_name);
        etQianming = (EditText) findViewById(R.id.ur_et_qianming);
        etWorkexp1 = (EditText) findViewById(R.id.ur_et_workexp1);
        etAliasname = (EditText) findViewById(R.id.ur_et_aliasname);
        etSeniority = (EditText) findViewById(R.id.ur_et_seniority);
        etGlory = (EditText) findViewById(R.id.ur_et_glory);
        etPresentjob = (EditText) findViewById(R.id.ur_et_presentjob);
        etInst = (EditText) findViewById(R.id.ur_et_inst);

        rbBoy = (RadioButton) findViewById(R.id.ur_rb_boy);
        rbGirl = (RadioButton) findViewById(R.id.ur_rb_girl);

        sharedPreferences = getSharedPreferences("data_dyk",0);

        sessionID = CookieHelper.getSessionID(sharedPreferences);
        etName.setText(sharedPreferences.getString("qryTname",""));
        etQianming.setText(sharedPreferences.getString("qryTsignature",""));
        etWorkexp1.setText(sharedPreferences.getString("qryTepc",""));
        etAliasname.setText(sharedPreferences.getString("qryTAliasname",""));
        etGlory.setText(sharedPreferences.getString("qryTglory",""));
        etSeniority.setText(sharedPreferences.getString("qryTseniorty",""));
        etPresentjob.setText(sharedPreferences.getString("qryTpresentjob",""));
        etInst.setText(sharedPreferences.getString("qryTinst",""));
        if (sharedPreferences.getString("qryTgender", "").equals("1")) {
            rbBoy.setChecked(true);
        }else if (sharedPreferences.getString("qryTgender", "").equals("0")) {
            rbGirl.setChecked(true);
        }

        qryTid = sharedPreferences.getString("qryTid","");
    }


    public void back(View view) {
        switch (view.getId()){
            case R.id.ur_back:
                finish();
                break;
            case R.id.ur_queren:
                if (TextUtils.isEmpty(etName.getText())||
                        TextUtils.isEmpty(etQianming.getText())||
                        TextUtils.isEmpty(etWorkexp1.getText())||
                        TextUtils.isEmpty(etAliasname.getText())||
                        TextUtils.isEmpty(etSeniority.getText())||
                        TextUtils.isEmpty(etGlory.getText())||
                        TextUtils.isEmpty(etPresentjob.getText())||
                        coverPic==null||idenPic==null||pfcfPic==null||teflPic==null) {

                    Toast.makeText(this, "您的简历中尚有未完善的部分\n请补充完整~", Toast.LENGTH_SHORT).show();
                }else {
                    progressDialog = ProgressDialog.show(this, null, "正在上传....", true, false);
                    name = etName.getText().toString();   //姓名
                    workExp1 = etWorkexp1.getText().toString();   //工作经历
                    qianMing = etQianming.getText().toString();   //个性签名
                    aliasname=etAliasname.getText().toString();  //昵称
                    seniority=etSeniority.getText().toString();   //教龄
                    glory=etGlory.getText().toString();              //光荣墙
                    presentJob=etPresentjob.getText().toString();  //现任工作
                    inst = etInst.getText().toString();         //教授乐器

                    int buttonId = radioGroup.getCheckedRadioButtonId();
                    if (buttonId==rbBoy.getId()){
                        sexID="1";
                    }else if (buttonId==rbGirl.getId()){
                        sexID="0";
                    }else{
                        Toast.makeText(UploadResume.this, "您还没选择性别", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    final String upLoadUrl = ThisUri.SERVER_YUMING+ThisUri.UPLOAD_RESUME;

                    final RequestParams params=new RequestParams(upLoadUrl);
                    //添加sessionID
                    params.addHeader("cookie", sessionID);
                    //开启multipart/form-data上传格式
                    params.setMultipart(true);
                    params.addBodyParameter("avatar", new File(coverPic));
                    params.addBodyParameter("idenpic",new File(idenPic));
                    params.addBodyParameter("teflpic",new File(teflPic));
                    params.addBodyParameter("pfcfpic",new File(pfcfPic));
                    params.addBodyParameter("memname", name);
                    params.addBodyParameter("aliasname", aliasname);
                    params.addBodyParameter("gender", sexID);
                    params.addBodyParameter("seniority",seniority);
                    params.addBodyParameter("signature", qianMing);
                    params.addBodyParameter("workepc", workExp1);
                    params.addBodyParameter("glory",glory);
                    params.addBodyParameter("presentjob",presentJob);
                    params.addBodyParameter("inst", inst);

                    if (!qryTid.equals("")) {
                        params.addBodyParameter("id",qryTid);
                        Log.e("test","修改老师资料 资料ID： "+qryTid);
                    }

                    UploadUtils.postData(params, new UploadUtils.UploadCallback() {
                        @Override
                        public void onFinish(String state) {

                            Message msg = handler.obtainMessage();
                            msg.what = 1;
                            msg.obj = state;

                            handler.sendMessage(msg);
                        }
                    });

                }
                break;
        }
    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String state= (String) msg.obj;
                    Log.e("test", "上传简历结果 " + state);
                    HashMap<String, Object> jsonFromLogin = LoginJsonUtils.getJsonFromLogin(state);
                    flag= (boolean) jsonFromLogin.get("success");

                    if (flag) {
                        Toast.makeText(UploadResume.this, "提交成功！", Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putString("qryTname",name);
                        edit.putString("qryTepc",workExp1);
                        edit.putString("qryTsignature",qianMing);
                        edit.putString("qryTAliasname",aliasname);
                        edit.putString("qryTseniorty",seniority);
                        edit.putString("qryTglory",glory);
                        edit.putString("qryTpresentjob",presentJob);
                        edit.putString("qryTgender",sexID);
                        edit.putString("qryTinst", inst);
                        edit.commit();
                        progressDialog.dismiss();
                        setResult(152);
                        finish();
                    }else{
                        Toast.makeText(UploadResume.this,"提交失败！",Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                    break;
                case 2:
                    String result= (String) msg.obj;
                    Gson gson=new Gson();
                    QryTeacher objBean = gson.fromJson(result, QryTeacher.class);
                    if (objBean.isSuccess()) {
                        if (objBean.getObj() != null) {
                            QryTeacher.ObjBean obj = objBean.getObj();
                            String avatar = obj.getAvatar();     //头像
                            String pfcfpic = obj.getPfcfpic();   //专业证
                            String teflpic = obj.getTeflpic();   //教师资格证
                            String idenpic = obj.getIdenpic();   //身份证
                            ImageLoader.getInstance().displayImage(avatar, ivCover);
                            ImageLoader.getInstance().displayImage(pfcfpic, ivTapPro);
                            ImageLoader.getInstance().displayImage(teflpic, ivTapTeach);
                            ImageLoader.getInstance().displayImage(idenpic, ivTapIdcard);

                            ivCover.setDrawingCacheEnabled(true);
                            Bitmap ivBmp = ivCover.getDrawingCache();
                            String ada = PhotoUtils.saveImg(ivBmp);
                            coverPic = ada;
                            ivCover.setDrawingCacheEnabled(false);



                        }
                    }
                    break;
            }
        }
    };

    public void getDiglog(){
        int maxNum=1;
        Intent intent=new Intent(UploadResume.this,MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA,true);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT,maxNum);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
        if (pathList != null && pathList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, pathList);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    public void takePhotoUR(View view) {
        switch (view.getId()){
            case R.id.ur_cover:        //头像
                clickTag=0;
                getDiglog();
                break;
            case R.id.ur_layout_idcard:   //身份证
                clickTag=1;
                getDiglog();
                break;
            case R.id.ur_layout_pro:      //专业证
                clickTag=2;
                getDiglog();
                break;
            case R.id.ur_layout_teach:  //教室资格证
                clickTag=3;
                getDiglog();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                pathList=data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);

                for (String s : pathList) {

                    if (clickTag==0){
                        coverPic=s;

                        PhotoUtils photoUtils1 = new PhotoUtils();
                        PhotoUtils.CompressOptions options1=new PhotoUtils.CompressOptions();
                        options1.uri=Uri.fromFile(new File(coverPic));
                        Bitmap bitmap1 = photoUtils1.compressFromUri(this, options1);

                        ivCover.setImageBitmap(bitmap1);
                    }else if (clickTag == 1) {
                        idenPic=s;

                        PhotoUtils photoUtils2 = new PhotoUtils();
                        PhotoUtils.CompressOptions options2=new PhotoUtils.CompressOptions();
                        options2.uri=Uri.fromFile(new File(idenPic));
                        Bitmap bitmap2 = photoUtils2.compressFromUri(this, options2);

                        ivTapIdcard.setImageBitmap(bitmap2);
                        btnIdcard.setVisibility(View.GONE);
                    }else if (clickTag == 2) {
                        pfcfPic=s;

                        PhotoUtils photoUtils3 = new PhotoUtils();
                        PhotoUtils.CompressOptions options3=new PhotoUtils.CompressOptions();
                        options3.uri=Uri.fromFile(new File(pfcfPic));
                        Bitmap bitmap3 = photoUtils3.compressFromUri(this, options3);

                        ivTapPro.setImageBitmap(bitmap3);
                        btnPro.setVisibility(View.GONE);
                    }else if (clickTag == 3) {
                        teflPic=s;

                        PhotoUtils photoUtils4 = new PhotoUtils();
                        PhotoUtils.CompressOptions options4=new PhotoUtils.CompressOptions();
                        options4.uri=Uri.fromFile(new File(teflPic));
                        Bitmap bitmap4 = photoUtils4.compressFromUri(this, options4);

                        ivTapTeach.setImageBitmap(bitmap4);
                        btnTeach.setVisibility(View.GONE);
                    }
                    clickTag=-1;
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    private void doPhoto(int requestCode,Intent data)
    {
        if(requestCode == SELECT_PIC_BY_PICK_PHOTO )
        {
            if(data == null)
            {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                return;
            }
            photoUri = data.getData();
            if(photoUri == null )
            {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                return;
            }
        }


        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor =  getContentResolver().query(photoUri,pojo,null,null,null);
        if(cursor != null )
        {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.e("test", "imagePath = " + picPath);

        if (clickTag==0){
            coverPic=picPath;

            PhotoUtils photoUtils1 = new PhotoUtils();
            PhotoUtils.CompressOptions options1=new PhotoUtils.CompressOptions();
            options1.uri=Uri.fromFile(new File(coverPic));
            Bitmap bitmap1 = photoUtils1.compressFromUri(this, options1);

            ivCover.setImageBitmap(bitmap1);
        }else if (clickTag == 1) {
            idenPic=picPath;

            PhotoUtils photoUtils2 = new PhotoUtils();
            PhotoUtils.CompressOptions options2=new PhotoUtils.CompressOptions();
            options2.uri=Uri.fromFile(new File(idenPic));
            Bitmap bitmap2 = photoUtils2.compressFromUri(this, options2);

            ivTapIdcard.setImageBitmap(bitmap2);
            btnIdcard.setVisibility(View.GONE);
        }else if (clickTag == 2) {
            pfcfPic=picPath;

            PhotoUtils photoUtils3 = new PhotoUtils();
            PhotoUtils.CompressOptions options3=new PhotoUtils.CompressOptions();
            options3.uri=Uri.fromFile(new File(pfcfPic));
            Bitmap bitmap3 = photoUtils3.compressFromUri(this, options3);

            ivTapPro.setImageBitmap(bitmap3);
            btnPro.setVisibility(View.GONE);
        }else if (clickTag == 3) {
            teflPic=picPath;

            PhotoUtils photoUtils4 = new PhotoUtils();
            PhotoUtils.CompressOptions options4=new PhotoUtils.CompressOptions();
            options4.uri=Uri.fromFile(new File(teflPic));
            Bitmap bitmap4 = photoUtils4.compressFromUri(this, options4);

            ivTapTeach.setImageBitmap(bitmap4);
            btnTeach.setVisibility(View.GONE);
        }
        clickTag=-1;
    }


    public void chooseSex(View view) {
        switch (view.getId()) {
            case R.id.ur_rb_boy:
                Log.e("test",rbBoy.getText().toString());
                break;
            case R.id.ur_rb_girl:
                Log.e("test",rbGirl.getText().toString());
                break;
        }
    }


}
